package org.pyframe.parser;

import java.util.ArrayList;
import java.util.List;


@SuppressWarnings("rawtypes")
public class Part {
	
	String name;
	String type;
	int length;
	String value;
	
	boolean ebcdic;
	boolean pack;

	public boolean isEbcdic() {
		return ebcdic;
	}

	public void setEbcdic(boolean ebcdic) {
		this.ebcdic = ebcdic;
	}	
	
	public boolean isPack() {
		return pack;
	}

	public void setPack(boolean pack) {
		this.pack = pack;
	}

	List arrValue = new ArrayList();
	
	public List getArrValue() {
		return arrValue;
	}

	public void setArrValue(List arrValue) {
		this.arrValue = arrValue;
	}

	public static Part createPart(String data) {
		String[] d = data.split(",", -1);
		Part part = new Part();
		part.setName(d[0].trim());
		part.setType(d[1].trim());
		part.setLength(Integer.parseInt(d[2].trim()));
		if (d.length > 3) {
			part.setValue(d[3]);
		}
		return part;
	}
	
	public int getLength() {
		return length;
	}
	public void setLength(int length) {
		this.length = length;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getValue() {
		if(value==null) {
			value = "";
		}
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	
	public String toString() {
		StringBuffer s = new StringBuffer();
		s.append("["+PacketTools.RPAD(name, 15, ' ')+"]");
		s.append("["+PacketTools.nvl(type, "N")+"]");
		s.append("["+PacketTools.LPAD(""+length, 3, ' ')+"]");
//		if(isPack()) {
//			s.append("[P]");
//		}else {
//			s.append("[X]");
//		}
		
		if("A".equals(type)) {
			s.append("["+arrValue.toString()+"]");
		}else {
			s.append("["+raw()+"]");
		}
		return s.toString();
	}
	
	public String raw() {
		return raw(this.value);
	}
	
	public String raw(String aValue) {
		if (length > 0) {
			String t = "";
			if ("C".equals(getType())) {
				t = PacketTools.LPAD(PacketTools.nvl(aValue, ""), length, '0');
			}else {
				t = PacketTools.RPAD(PacketTools.nvl(aValue, ""), length, ' ');
			}
			byte[] src = t.getBytes();
			byte[] dst = new byte[length];
			System.arraycopy(src, 0, dst, 0, length);
			return new String(dst);
		}else {
			return aValue;
		}
	}

	
}
